#!/usr/bin/env python
#coding:utf-8

import serial
import threading
import time

class ErrorException(Exception):
    pass

class DLRS1A(object):
    def __init__(self, devicecnt, port, baudrate = 9600, bytesize = 8, parity = 'N', stopbits = 1):
        self.devicecnt = devicecnt
        self.port = serial.Serial(port, baudrate, bytesize, parity, stopbits)
        self.port.setTimeout(5)
        self.lock = threading.Lock()
        
    def M0(self):
        with self.lock:
            x = self.port.write('M0\x0D\x0A')
            time.sleep(0.1)
            n = self.port.inWaiting()
            r = self.port.read(n)
            #print r
            if r.startswith('ER'):
                raise ErrorException('%s response %s error' % (r[2:4], r[5:7]))
            vals = r[3:len(r)-2].split(',')
            try:
                return tuple([float(v) for v in vals])
            except:
                return tuple([0.0 for v in vals])
        
if __name__ == '__main__':
    dlrs1 = DLRS1A(6, 'COM1', 9600, 8, 'N', 1)
    while True:
        print "Res:", dlrs1.M0()
